<?php
// +----------------------------------------------------------------------
// | Just do it
// +----------------------------------------------------------------------
// | Author: shioujun <shioujun@gmail.com>
// +----------------------------------------------------------------------
// | Since: 2014-08-05 15:16
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Controller;
use Think\Model;
use Huodong\Model\PayModel;
use Common\Model\OpenIdModel as OpenId;

class WeixinController extends BaseController
{
    /**
     * 微信用户
     * @return [type] [description]
     */
    public function index()
    {
        $controller = I( 'get._c' );
        $action     = I( 'get._a' );
        //数据接口，转发到相应的action
        if( $action )
        {
            $controller = $controller ? $controller : CONTROLLER_NAME;
            R($controller."/".$action);
            return true;
        }

        $this->display();
    }

    /**
     * [userdata description]
     * @return [type] [description]
     */
    public function userdata(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = "ok";
        $ret['content'] = array();

        try{
            $offset = I("iDisplayStart",0,"intval");

            $size = I("iDisplayLength",10,"intval");
//             $offset = ($page - 1) * $size;

            $where = array();
            $keyword = I('sSearch');
            if( $keyword ) {
                $where['nickname']  = array('like','%'.$keyword.'%');
                $where['code']  = array('like','%'.$keyword.'%');
                $where['code2']  = array('like','%'.$keyword.'%');
                $where['_logic'] = 'or';
            }
            $order = D("WeixinUser");
            $data = $order->where( $where )->limit("{$offset},{$size}")->order("id desc")->select();
            header("sql : ".$order->getLastSql() );
            
            $ids = array();
            foreach ($data as $key=>$val){
            	$ids[ $val['id'] ] = $val['id'];
            }
          
            $is_focus_data = array();
            
            $ids = array_values($ids);
            if( $ids ){
	            $where2 = array();
	            $where2['uid'] = array('in',$ids);
	            $where2['wxhao'] = C('WX_HAO');
	            $open_obj = D('openid');
	            $openids = $open_obj->where($where2)->select();
	            foreach ($openids as $key2=>$open_item){
	            	$is_focus_data[$open_item['uid']] = $open_item['state'];
	            }
            }
            
            
            foreach ($data as $key => $value) {
                $data[$key]['openid'] = $value['openid']?$value['openid']:'';
                $nickname = $value['nickname'] ? $value['nickname'] : "匿名";
                $nickname = "<a href='http://".C('front_domain')."/my/account/openid/".$value['openid']."' target='_blank'>".$nickname."</a>";
                $data[$key]['nickname'] = $nickname;

                $logo = $value['logo'] ? $value['logo'] : '/static/images/noHead.jpg';
                $data[$key]['logo'] = '<a href="'.$logo.'" target="_blank"><img src="'.$logo.'" style="width:30px;height:30px;"/></a>';

                $url = '#'.U("Weixin/shouyi", "id=".$value['id'] );
                $data[$key]['total_money']  = '<a target="_self" href="'.$url.'" class="charts-comments" title="点击查看收益明细">'.$value['total_money'].'</a>';

                $value['state'] = $is_focus_data[$value['id']] ?1 : 0;
                
                $state = '';
                if( $value['state'] == 1 ){
                    $state = '<button class="btn btn-xs btn-success">正关注</button>';
                }elseif($value['state'] == 0 ){
                    $state = '<button class="btn btn-xs btn-warning">取消关注</button>';
                }
                $data[$key]['state']  =  $state;
                $data[$key]['updatetime']  =  $value['updatetime'];
                $data[$key]['option']  =  '<a target="_self" class="mycode" href="javascript:void(0);" data-id="'.$value['id'].'" data-code="'.$value['code2'].'">专属推广码</a>';

                $data[$key]['code'] = $value['code2']?$value['code2']:$value['code'];
            }
            $total = $order->where( $where )->count();

            $rs1 = array();
            $rs1['data'] = $data?$data:array();
            $ret['iTotalDisplayRecords'] = $total?$total:0;
            $ret['iTotalRecords'] = $total?$total:0;

            $ret['content'] = $rs1;

        }catch(\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }
        $this->ajaxReturn($ret);
    }

    /**
     * [userdata description]
     * @return [type] [description]
     */
    public function usercode(){
        $ret = array();
        $ret['status'] = 200;
        $ret['msg'] = "ok";
        $ret['content'] = array();

        try{
            $uid = I('id',0,'intval');
            $code = I('code','','trim');

            $u = D('User');
            $where = array();
            $where['code'] = $code;
            if( !empty($code) ){
                $where['code2'] = $code;
                $where['_logic'] = 'OR';
            }
            $userinfo = $u->where( $where )->find();
            if( $userinfo ){
                E('该推广码已经存在');
            }

            $where = array();
            $where['id'] = $uid;
            $update = array();
            $update['code2'] = $code;
            $rs = $u->where($where)->save($update);
            if( $rs===false ){
                E("设置失败!");
            }
            if( $code ){
                $where = array();
                $where['id'] = $uid;
                $userinfo = $u->where($where)->find();
                $content = "亲，为感谢你对【".C('title')."】的支持，你的推广码升级为：".$code ."\n原推广码：{$userinfo['code']} 可以继续使用/::)";
                $rs = txtMessage($userinfo['openid'],$content);
                //$this->log( json_encode($rs) );
            }
        }catch(\Exception $e){
            $ret['status'] = $e->getCode();
            $ret['msg'] = $e->getMessage();
        }
        $this->ajaxReturn($ret);
    }


}
